import { defineStore } from 'pinia';
import { loginApi, registerApi } from '../../api/auth';
import { LoginParams, RegisterParams } from '../../types/user';
import { ElMessage } from 'element-plus';

/**
 * 登录状态管理 Pinia Store
 * 包含登录参数、认证信息和登录/注册功能
 */
export const useLoginStore = defineStore('login', {
    // 状态定义，返回一个对象
    state: () => ({
        loginParams: {
            email: '',
            password: '',
            code: '',
            mode: '',
            cellphone: ''
        } as LoginParams,
        cookie: '',
        xApiKey: '4e7kGzY6w9kQpFvL3uXbRzTp8aN5mJw2',
        registerParams: {
            username: '',
            age: 0,
            email: '',
            code: '',
            password: '',
            repassword: ''
        } as RegisterParams
    }),

    // 获取器，类似 Vuex 的 getters
    getters: {
        getCookie: (state) => state.cookie,
        getXApiKey: (state) => state.xApiKey
    },

    // 动作，包含异步操作和状态更新
    actions: {
        /**
         * 用户登录
         * @param params 登录参数
         */
        async login(params: LoginParams) {
            try {
                const response = await loginApi(params);
                if (response.code === 200) {
                    this.cookie = response.result.token;
                    ElMessage.success('登录成功');
                    return response.result;
                }
                ElMessage.error(response.message || '登录失败');
                return null;
            } catch (error: any) {
                ElMessage.error(error.message || '登录请求失败');
                return null;
            }
        },

        /**
         * 用户注册
         * @param params 注册参数
         */
        async register(params: RegisterParams) {
            try {
                const response = await registerApi(params);
                if (response.code === 200) {
                    ElMessage.success(response.message || '注册成功');
                    return response.result;
                }
                ElMessage.error(response.message || '注册失败');
                return null;
            } catch (error: any) {
                ElMessage.error(error.message || '注册请求失败');
                return null;
            }
        },

        /**
         * 重置登录参数
         */
        resetLoginParams() {
            this.loginParams = {
                email: '',
                password: '',
                code: '',
                mode: '',
                cellphone: ''
            };
        },

        /**
         * 重置注册参数
         */
        resetRegisterParams() {
            this.registerParams = {
                username: '',
                age: 0,
                email: '',
                code: '',
                password: '',
                repassword: ''
            };
        }
    }
});